﻿using ConfExpert.Forms.Base;
using ConfExpert.Forms.Depo;
using ConfExpert.Properties;

using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace ConfExpert.Forms.SatinAlma.YeniYapi
{
    public partial class NumuneTopGirisi : XForm
    {
        public NumuneTopGirisi()
        {
            InitializeComponent();
        }

        private void NumuneGirisi_Load(object sender, EventArgs e)
        {
            gridView1.Init("DX_GetNumuneGirisi", WhoAmI, barCheckItem1.Checked);

            DataTable dtShelf = ExecuteDataTable("DX_GetNumuneRaflari");
            RepositoryItemGridLookUpEdit riShelf = GetCustomGLE(dtShelf, "Name", "ShelfId");
            gridView1.Columns["ShelfId"].ColumnEdit = riShelf;
            ((RepositoryItemGridLookUpEdit)(gridView1.Columns["ShelfId"].ColumnEdit)).TextEditStyle = TextEditStyles.DisableTextEditor;

            gridView1.FormatAsNumber(1, "Qty");
            gridView1.AddSummary("Qty");
            gridView1.SetCaptions("DX_NumuneGirisiId:#");
            gridView1.MakeColumnsReadOnly("GelisTarihi", "GelisPartisiId", "RollId");
            gridView1.ShowingEditor += gridView1_ShowingEditor;
            gridView1.FormatAsDateTime("GelisTarihi");

            gridView1.BestFitColumns();

            DataTable dt = gridView1.DataTable();
            gridView1.AddAutoIncrementalPK("DX_NumuneGirisiId");
            
            //dt.PrimaryKey = new DataColumn[] { gridView1.DataTable().Columns["DX_NumuneGirisiId"] };
            //dt.AddAutoIncrementalColumn("DX_NumuneGirisiId");
            //dt.Columns["DX_NumuneGirisiId"].AutoIncrementSeed = -1;
            //dt.Columns["DX_NumuneGirisiId"].AutoIncrementStep = -1;
            //dt.Columns["DX_NumuneGirisiId"].AutoIncrement = true;
            dt.TableNewRow += NumuneGirisi_TableNewRow;
            bbiKaydet.ItemClick += bbiKaydet_ItemClick;

            gridView1.MakeCompulsory("ProductId", "Qty");
            gridView1.YanYanaGetir("DX_NumuneGirisiId:UserId");
            GridManager gm = GridManager.GetManager(gridView1);
            //gm.GridMenu.AddMenu("Giriş+Çıkış yap", GirisCikis);
            gm.GridMenu.AddMenu("Kod sihirbazı", KodSihirbazi_Click, Resources.wizardcontrol);
            //gm.GridMenu.AddMenu("Stok kartı düzenle", StokKartlariniDuzenle);

            //gridView1.MakeColumnInvisible("UserId");

            gridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            barCheckItem1.CheckedChanged += barCheckItem1_CheckedChanged;
            gridView1.ValidatingEditor += gridView1_ValidatingEditor;
        }

        private void gridView1_ValidatingEditor(object sender, BaseContainerValidateEditorEventArgs e)
        {
            GridView view = sender as GridView;
            if (view.FocusedColumn.FieldName == "Qty")
            {
                //Get the currently edited value 
                double qty = Convert.ToDouble(e.Value);
                //Specify validation criteria 
                //if (qty < 0)
                //{
                //    e.Valid = false;
                //    e.ErrorText = "Enter a positive value";
                //}
                if (qty > 5)
                {
                    e.Valid = false;
                    e.ErrorText = "Metraj 5 mt.nin üstünde olamaz !";
                }
            }
        }

        void gridView1_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            DataRow dr = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            if (dr != null)
                e.Cancel = dr["RollId"].ToInt() > 0;
            else
                e.Cancel = false;
        }


        void KodSihirbazi_Click(object sender, EventArgs e)
        {
            gridView1.EndEditing();

            List<POKodSihirbazi.Kod> kodlar = new List<POKodSihirbazi.Kod>();
            foreach (int rowHandle in gridView1.GetSelectedRows())
            {
                DataRow dr = gridView1.GetDataRow(rowHandle);

                int productId = dr["ProductId"].ToInt(-1);
                if (productId == -1)
                {
                    POKodSihirbazi.Kod kod = new POKodSihirbazi.Kod();

                    kod.ProductId = dr["ProductId"].ToInt(-1);
                    kod.KCustomerId = 437;    //Destex

                    kod.UreticiKodu = dr["UreticiKodu"].ToStr();
                    kod.KVendorId = dr["UreticiId"].ToInt(-1);
                    //kod.KaliteAciklama = dr["TalepTeknikOzellik"].ToStr();
                    kod.POLinesId = dr["DX_NumuneGirisiId"].ToInt(-1);
                    kod.RowHandle = rowHandle;

                    if (kod.UreticiKodu != string.Empty)
                        kodlar.Add(kod);
                }
            }

            if (kodlar.Count > 0)
                using (POKodSihirbazi ks = new POKodSihirbazi(kodlar))
                {
                    if (ks.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        foreach (POKodSihirbazi.Kod kod in ks.Kodlar)
                            if (kod.ProductId > 0)
                                gridView1.SetRowCellValue(kod.RowHandle, "ProductId", kod.ProductId);

                        //btnKaydet.PerformClick();

                        //GetDetails("PO", "GetPO2", POId);
                    }
                }
        }

        void StokKartlariniDuzenle(object sender, EventArgs e)
        {
            List<string> kodlar = new List<string>();
            foreach (int rowHandle in gridView1.GetSelectedRows())
            {
                DataRow dr = gridView1.GetDataRow(rowHandle);

                if (dr["ProductId"] != DBNull.Value)
                    kodlar.Add(dr["ProductId"].ToString());
            }

            if (kodlar.Count > 0)
                using (StokKartiDuzenle ks = new StokKartiDuzenle(string.Join(";", kodlar.ToArray())))
                {
                    ks.ShowDialog();
                    gridView1.RefreshData();
                }
            else
                XtraMessageBox.Show("Seçtikleriniz içinde, ProductId'si setlenmiş satır yok.");
        }

        void barCheckItem1_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.RefreshDataSource("DX_GetNumuneGirisi", WhoAmI, barCheckItem1.Checked);
            gridView1.BestFitColumns();
        }

        void NumuneGirisi_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["UserId"] = WhoAmI;
            e.Row["Qty"] = 2;
        }

        void bbiKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.EndEditing();
            if (checkEmpty(gridView1.DataTable(), "Qty"))
            {
                XtraMessageBox.Show("Zorunlu alanları doldurduktan sonra tekrar deneyin", "Eksik giriş", MessageBoxButtons.OK);
                return;
            }

            //gridView1.Update("", "DX_NumuneGirisi");
            //gridView1.VeriyiGuncelle("DX_GetNumuneGirisi", WhoAmI, barCheckItem1.Checked);

            /*
            List<string>lst = new List<string>();
            foreach (DataRow r in gridView1.DataTable().Rows)
                if (r["RollId"].ToInt() == 0)
                    lst.Add(r["DX_NumuneGirisiId"].ToStr());

            //string ids = gridView1.GetSelectedValues("DX_NumuneGirisiId");
            string ids = string.Join(",", lst.ToArray());
             */
            List<int> mgkIds = new List<int>();
            foreach (int rowHandle in gridView1.GetSelectedRows())
            {
                DataRow dr = gridView1.GetDataRow(rowHandle);
                if (dr["ProductId"] == DBNull.Value)
                    mgkIds.Add(dr["DX_NumuneGirisiId"].ToInt(-1));
            }

            if (mgkIds.Count > 0)
                if (XtraMessageBox.Show("Seçtiğiniz satırlarda ProductId'si setlenmemiş " + mgkIds.Count + " satır var. Bunları Kod Sihirbazında setlemek ister misiniz?", "DİKKAT!", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    KodSihirbazi_Click(sender, e);

            gridView1.Update("", "DX_NumuneGirisi");
            gridView1.RefreshDataSource("DX_InsNumuneGirisi", WhoAmI, barCheckItem1.Checked);
            gridView1.BestFitColumns();
        }
    }
}
